package main

import "fmt"

/*
给你两个 非空 的链表，表示两个非负的整数。
它们每位数字都是按照 逆序 的方式存储的，并且每个节点只能存储 一位 数字。

请你将两个数相加，并以相同形式返回一个表示和的链表。

你可以假设除了数字 0 之外，这两个数都不会以 0 开头。

输入：l1 = [2,4,3], l2 = [5,6,4]
输出：[7,0,8]
解释：342 + 465 = 807.

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
*/

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

type ListNode struct {
	Val  int
	Next *ListNode
}

func addTwoNumbers1(l1 *ListNode, l2 *ListNode) *ListNode {
	l := &ListNode{}
	tmp, tmp2 := l, l
	carry := 0
	for l1 != nil || l2 != nil || carry > 0 {
		switch {
		case l1 == nil && l2 != nil:
			carry += l2.Val
			tmp.Val = carry % 10
			l2 = l2.Next
		case l1 != nil && l2 == nil:
			carry += l1.Val
			tmp.Val = carry % 10
			l1 = l1.Next
		case l1 != nil && l2 != nil:
			carry += l1.Val + l2.Val
			tmp.Val = carry % 10
			l1, l2 = l1.Next, l2.Next
		default:
			tmp.Val = carry
		}

		tmp2 = tmp
		tmp.Next = &ListNode{}
		tmp = tmp.Next
		carry /= 10
	}
	tmp2.Next = nil

	return l

}

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	l := &ListNode{}
	tmp, carry := l, 0

	for l1 != nil || l2 != nil {
		if l1 != nil {
			carry += l1.Val
			l1 = l1.Next
		}
		if l2 != nil {
			carry += l2.Val
			l2 = l2.Next
		}

		tmp.Next = &ListNode{Val: carry % 10}
		tmp = tmp.Next
		carry /= 10
	}
	if carry > 0 {
		tmp.Next = &ListNode{Val: carry}
	}

	return l.Next
}

func main() {
	test1()
	test2()
	test3()
}

// l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]  l = [8,9,9,9,0,0,0,1]
func test3() {
	l1 := &ListNode{Val: 9}
	l1.Next = &ListNode{Val: 9}
	l1.Next.Next = &ListNode{Val: 9}
	l1.Next.Next.Next = &ListNode{Val: 9}
	l1.Next.Next.Next.Next = &ListNode{Val: 9}
	l1.Next.Next.Next.Next.Next = &ListNode{Val: 9}
	l1.Next.Next.Next.Next.Next.Next = &ListNode{Val: 9}

	l2 := &ListNode{Val: 9}
	l2.Next = &ListNode{Val: 9}
	l2.Next.Next = &ListNode{Val: 9}
	l2.Next.Next.Next = &ListNode{Val: 9}

	l := addTwoNumbers(l1, l2)
	for l != nil {
		fmt.Print(l.Val)
		l = l.Next
	}
	fmt.Println()
}

// l1 = [0], l2 = [0]  l = [7,0,8]
func test2() {
	l1 := &ListNode{}

	l2 := &ListNode{}

	l := addTwoNumbers(l1, l2)
	for l != nil {
		fmt.Print(l.Val)
		l = l.Next
	}
	fmt.Println()
}

// l1 = [2,4,3], l2 = [5,6,4]  l = [7,0,8]
func test1() {
	l1 := &ListNode{Val: 2}
	l1.Next = &ListNode{Val: 4}
	l1.Next.Next = &ListNode{Val: 3}

	l2 := &ListNode{Val: 5}
	l2.Next = &ListNode{Val: 6}
	l2.Next.Next = &ListNode{Val: 4}

	l := addTwoNumbers(l1, l2)
	for l != nil {
		fmt.Print(l.Val)
		l = l.Next
	}

	fmt.Println()
}
